import { useCallback } from "react";
import { useMountedRef } from "./useMountRef";

/**
 * 安全的 dispatch hooks，避免在组件卸载的情况下去改变状态
 * @param dispatch
 * @returns
 */
export function useSafeDispatch<T>(dispatch: (...args: T[]) => void) {
  const mountedRef = useMountedRef();
  return useCallback(
    (...args: T[]) => (mountedRef.current ? dispatch(...args) : void 0),
    [dispatch, mountedRef]
  );
}
